﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UI
{
    public class UIFieldRunMapTeamMember : MonoBehaviour
    {
        public GameObject template;
        public UIGrid grid;

        List<GameObject> caches = new List<GameObject>();

        public void Init()
        {
            if (StaticData.playerData.team != null)
            {
                //StopCoroutine(_InitList());
                //StartCoroutine(_InitList());
                Refresh();
            }
            else
            {
                Debug.LogError("[Error] team list null");
            }
        }

        bool needRefresh = false;
        void Refresh()
        {
            foreach (var cache in caches)
            {
                Destroy(cache);
            }
            caches.Clear();

            int index = 0;
            foreach (var member in StaticData.playerData.team.memberList)
            {
                var obj = Instantiate(template) as GameObject;
                obj.transform.SetParent(grid.transform);
                obj.transform.localScale = Vector3.one;
                grid.Reposition();
                obj.SetActive(true);
                caches.Add(obj);
                var script = obj.GetComponent<UIFieldRunMapTeamTemplate>();
                script.Init(member, index++ == 0);
            }
            grid.Reposition();
            needRefresh = true;
        }

        void Update()
        {
            if(needRefresh)
            {
                grid.Reposition();
                needRefresh = false;
            }
        }

        /*
        IEnumerator _InitList()
        {
            foreach (var cache in caches)
            {
                Destroy(cache);
            }
            caches.Clear();
            yield return null;
            int index = 0;
            foreach (var member in StaticData.playerData.team.memberList)
            {
                var obj = Instantiate(template) as GameObject;
                obj.transform.SetParent(grid.transform);
                obj.transform.localScale = Vector3.one;
                grid.Reposition();
                obj.SetActive(true);
                caches.Add(obj);
                var script = obj.GetComponent<UIFieldRunMapTeamTemplate>();
                script.Init(member, index++ == 0);
            }
            yield return null;

        }
        */

        public void Exit()
        {
            //StopAllCoroutines();
        }
    }
}